package com.sxfq.loansupermarket.backsystem.modular.system.controller;

import com.sxfq.loansupermarket.backsystem.common.annotion.Permission;
import com.sxfq.loansupermarket.backsystem.common.annotion.log.BussinessLog;
import com.sxfq.loansupermarket.backsystem.common.constant.Dict;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.ConstantFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.node.ZTreeNode;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.DeptMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogObjectHolder;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.util.Convert;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.system.dao.DeptDao;
import com.sxfq.loansupermarket.backsystem.modular.system.service.IDeptService;
import com.sxfq.loansupermarket.backsystem.modular.system.warpper.DeptWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 部门控制器
 *
 * @author fengshuonan
 * @Date 2017年2月17日20:27:22
 */
@Controller
@RequestMapping("/dept")
public class DeptController extends BaseController {
    @Resource
    DeptDao deptDao;

    @Resource
    DeptMapper deptMapper;

    @Autowired
    UserMapper userMapper;

    @Resource
    IDeptService deptService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/system/dept/";

    /**
     * 跳转到部门管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "dept.html";
    }

    /**
     * 跳转到添加部门
     */
    @RequestMapping("/dept_add")
    public String deptAdd() {
        return PREFIX + "dept_add.html";
    }

    /**
     * 跳转到添加积分
     */
    @RequestMapping("/add_fen/{deptId}")
    public String addFen(@PathVariable Integer deptId, Model model) {
        Dept dept = deptMapper.selectById(deptId);
        model.addAttribute("dept", dept);
        model.addAttribute("province", ShiroKit.getSessionAttr("province"));
        model.addAttribute("cities", ShiroKit.getSessionAttr("cities"));
        return PREFIX + "dept_add_fen.html";
    }

    /**
     * 跳转到折扣审核控制
     */
    @RequestMapping("/to_auditswitch/{deptId}")
    public String to_auditswitch(@PathVariable Integer deptId, Model model) {
        Dept dept = deptMapper.selectById(deptId);
        model.addAttribute("dept", dept);
        return PREFIX + "audit_switch.html";
    }

    /**
     * 跳转到科室审核控制
     */
    @RequestMapping("/to_auditOfDept/{deptId}")
    public String to_auditOfDept(@PathVariable Integer deptId, Model model) {
        Dept dept = deptMapper.selectById(deptId);
        model.addAttribute("dept", dept);
        return PREFIX + "audit_dept.html";
    }

    /**
     * 设置扎帐时间
     */
    @RequestMapping("/to_sttleAccountsTime/{deptId}")
    public String to_sttleAccountsTime(@PathVariable Integer deptId, Model model) {
        Dept dept = deptMapper.selectById(deptId);
        model.addAttribute("dept", dept);
        return PREFIX + "sttle_accounts.html";
    }

    /**
     * 添加积分
     */
    @RequestMapping(value = "/setproportional")
    @ResponseBody
    public int setproportional(String proportional, String id) {
        String sql = "update dept t set t.proportional='" + proportional + "' where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 设置扎帐时间
     */
    @RequestMapping(value = "/sttleAccountsTime")
    @ResponseBody
    public int sttleAccountsTime(String id, String sttleAccountsHour, String sttleAccountsMinute, String sttleAccountsSecond) {
        String sql = "update dept t set t.sttle_accounts_hour='" + sttleAccountsHour + "'," +
                " t.sttle_accounts_minute='" + sttleAccountsMinute + "'," +
                " t.sttle_accounts_second='" + sttleAccountsSecond + "' where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 控制审批
     */
    @RequestMapping(value = "/setauditswitch")
    @ResponseBody
    public int setauditswitch(String id, String auditswitch, Integer levelOneAudit, Integer levelTwoAudit) {
        String sql = "update dept t set t.auditswitch='" + auditswitch + "',t.level_one_audit='" + levelOneAudit + "',t.level_two_audit='" + levelTwoAudit + "' where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 控制科室审批
     */
    @RequestMapping(value = "/updateAuditOfDept")
    @ResponseBody
    public int updateAuditOfDept(String id, String auditofdept) {
        String sql = "update dept t set t.auditofdept='" + auditofdept + "' where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 跳转到修改部门
     */
    @RequestMapping("/dept_update/{deptId}")
    public String deptUpdate(@PathVariable Integer deptId, Model model) {
        Dept dept = deptMapper.selectById(deptId);
        model.addAttribute(dept);
        model.addAttribute("pName", ConstantFactory.me().getDeptName(dept.getPid()));
        LogObjectHolder.me().set(dept);
        model.addAttribute("province", ShiroKit.getSessionAttr("province"));
        model.addAttribute("cities", ShiroKit.getSessionAttr("cities"));
        return PREFIX + "dept_edit.html";
    }

    /**
     * 获取部门的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        List<ZTreeNode> tree = this.deptDao.tree();
        tree.add(ZTreeNode.createParent());
        return tree;
    }

    /**
     * 新增部门
     */
    @BussinessLog(value = "添加部门", key = "simplename", dict = Dict.DeptDict)
    @RequestMapping(value = "/add")
    @Permission
    @ResponseBody
    public Object add(Dept dept) {
        if (ToolUtil.isOneEmpty(dept, dept.getSimplename())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        dept.setSttleAccountsHour("00");
        dept.setSttleAccountsMinute("00");
        dept.setSttleAccountsSecond("00");
        deptSetPids(dept);  //完善pids,根据pid拿到pid的pids
        this.deptMapper.insert(dept);
        String sql = "update dept set num=id where simplename='" + dept.getSimplename() + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 获取所有部门列表
     */
    @RequestMapping(value = "/list")
    @Permission
    @ResponseBody
    public Object list(String condition) {
        List<Map<String, Object>> list = this.deptDao.list(condition);
        return super.warpObject(new DeptWarpper(list));
    }

    /**
     * 部门详情
     */
    @RequestMapping(value = "/detail/{deptId}")
    @Permission
    @ResponseBody
    public Object detail(@PathVariable("deptId") Integer deptId) {
        return deptMapper.selectById(deptId);
    }

    /**
     * 修改部门
     */
    @BussinessLog(value = "修改部门", key = "simplename", dict = Dict.DeptDict)
    @RequestMapping(value = "/update")
    @Permission
    @ResponseBody
    public Object update(Dept dept) {
        if (ToolUtil.isEmpty(dept) || dept.getId() == null) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        deptSetPids(dept);
        deptMapper.updateById(dept);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除部门
     */
    @BussinessLog(value = "删除部门", key = "deptId", dict = Dict.DeleteDict)
    @RequestMapping(value = "/delete")
    @Permission
    @ResponseBody
    public Object delete(@RequestParam String deptId) {
        LogObjectHolder.me().set(ConstantFactory.me().getDeptName(deptId));//缓存被删除的部门名称
        deptService.deleteDept(deptId);
        return SUCCESS_TIP;
    }

    private void deptSetPids(Dept dept) {
        if (ToolUtil.isEmpty(dept.getPid()) || dept.getPid().equals("0")) {
            dept.setPid("0");
            dept.setPids("[0],");
        } else {
            String pid = dept.getPid();
            Dept temp = deptMapper.selectById(pid);
            String pids = temp.getPids();
            dept.setPid(pid);
            dept.setPids(pids + "[" + pid + "],");
        }
    }

    @RequestMapping(value = "/getAreaList", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getList() {
        String sql = "select area_abbreviation as areaAbbreviation,area as area from dept a where length(a.pids)>4 " +
                " and version='" + ShiroKit.getSessionAttr("companyVersion") + "' group by a.area order by a.num desc";
        return sqlMapper.selectList(sql);
    }

    @RequestMapping(value = "/getListByArea", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getListByArea(String area) {
        if (StringUtil.isNotEmpty(area)) {
            String areaByAreaList = area + "byAreaList";
            if (ShiroKit.getSessionAttr(areaByAreaList) == null) {
                String getList = "select simplename as simplename from dept a where length(a.pids)>4 and area_abbreviation='" + area + "'";
                ShiroKit.setSessionAttr("" + areaByAreaList + "", sqlMapper.selectList(getList));
                return ShiroKit.getSessionAttr(areaByAreaList);
            } else {
                return ShiroKit.getSessionAttr(areaByAreaList );
            }
        } else {
            if (ShiroKit.getSessionAttr("byAreaList") == null) {
                String getList = "select simplename as simplename from dept a where length(a.pids)>4 and version='" + ShiroKit.getSessionAttr("companyVersion") + "'";
                ShiroKit.setSessionAttr("byAreaList", sqlMapper.selectList(getList));
                return ShiroKit.getSessionAttr("byAreaList");
            } else {
                return ShiroKit.getSessionAttr("byAreaList");
            }
        }
    }

    /**
     * 获取角色列表
     */
    @RequestMapping(value = "/deptTreeListByUserId/{userId}")
    @ResponseBody
    public List<ZTreeNode> roleTreeListByUserId(@PathVariable Integer userId) {
        User theUser = this.userMapper.selectById(userId);
        String deptid = theUser.getDeptid();
        if (ToolUtil.isEmpty(deptid)) {
            List<ZTreeNode> roleTreeList = this.deptDao.deptTreeList();
            return roleTreeList;
        } else {
            String[] strArray = Convert.toStrArray(",", deptid);
            List<ZTreeNode> roleTreeListByUserId = this.deptDao.deptTreeListByRoleId(strArray);
            return roleTreeListByUserId;
        }
    }
}